package com.jiwang.mail.util.mail;

import com.jiwang.mail.dto.QueryMailInfo;
import com.jiwang.mail.dto.SendMailInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import javax.mail.Session;
import java.util.Date;
import java.util.Properties;

/**
 * @author 沈伟峰
 */
@Component
public class MailUtil {

    private static MailUtil mailUtil;
    @Autowired
    private MailProperties properties;

    /**
     * 检测是否为简单邮件
     *
     * @param info 邮件信息
     * @return 检测结果
     */
    public static boolean isSimpleMail(SendMailInfo info) {
        return ObjectUtils.isEmpty(info.getFiles()) && !info.isHtml();
    }

    /**
     * 检测邮件是否具有必要信息
     *
     * @param info 邮件信息
     * @return 检测结果
     */
    public static boolean checkMail(SendMailInfo info) {
        return !(ObjectUtils.isEmpty(info.getFrom())
                || ObjectUtils.isEmpty(info.getTo())
                || ObjectUtils.isEmpty(info.getSubject())
                || ObjectUtils.isEmpty(info.getText())
                || ObjectUtils.isEmpty(info.getHost()));
    }

    /**
     * 创建 session 连接
     *
     * @param info 连接信息
     * @return session 对象
     */
    public static Session createSession(QueryMailInfo info) {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", info.getProtocol());
        props.setProperty("mail.imap.host", info.getHost());
        props.setProperty("mail.imap.port", String.valueOf(info.getPort()));
        return Session.getInstance(props);
    }

    /**
     * 如果邮件有可填充的缺省信息，则填充缺省信息
     *
     * @param info 邮件信息
     * @return 是否有填充
     */
    public static boolean fixDefault(SendMailInfo info) {
        boolean flag = false;
        if (ObjectUtils.isEmpty(info.getDate())) {
            flag = true;
            info.setDate(new Date());
        }
        if (ObjectUtils.isEmpty(info.getEncoding())) {
            flag = true;
            info.setEncoding(mailUtil.properties.getEncoding());
        }
        if (ObjectUtils.isEmpty(info.getPort())) {
            flag = true;
            info.setPort(mailUtil.properties.getSendPort());
        }
        if (ObjectUtils.isEmpty(info.getProtocol())) {
            flag = true;
            info.setProtocol(mailUtil.properties.getSendProtocol());
        }
        return flag;
    }

    @PostConstruct
    private void init() {
        mailUtil = this;
    }

}
